package com.lzj.test3;

import android.content.Context;
import android.graphics.Point;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class FloatingView extends LinearLayout {

    private Context context;
    private WindowManager windowManager;

    public FloatingView(Context mcontext) {
        super(mcontext);
        context = mcontext;
        windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

        initView();
    }

    private void initView() {
        inflate(context, R.layout.float_win_layout, this);
        TextView mTv_t = findViewById(R.id.mTv_t);
    }

    private int x;
    private int y;
    private int DOWNx;
    private int DOWNy;

    private String TAG = "FloatingView";

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                x = (int) event.getRawX();
                y = (int) event.getRawY();

                DOWNx = (int) event.getRawX();
                DOWNy = (int) event.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                int nowX = (int) event.getRawX();
                int nowY = (int) event.getRawY();
                int movedX = nowX - x;
                int movedY = nowY - y;
                x = nowX;
                y = nowY;

                WindowManager.LayoutParams layoutParams = (WindowManager.LayoutParams) this.getLayoutParams();
                layoutParams.x = layoutParams.x + movedX;
                layoutParams.y = layoutParams.y + movedY;
                windowManager.updateViewLayout(this, layoutParams);
                break;
            case MotionEvent.ACTION_UP:
                int upnowX = (int) event.getRawX();
                int upnowY = (int) event.getRawY();
                int upmovedX = upnowX - DOWNx;
                int upmovedY = upnowY - DOWNy;
                if (Math.abs(upmovedX)<5 && Math.abs(upmovedY)<5){
                    Toast.makeText(context, "点击了球球", Toast.LENGTH_LONG).show();
                }
                break;
        }
        return true;
    }
}
